#include "Thread.h"
#include "CurrentThread.h"

#include <semaphore.h>

std::atomic_int Thread::numCreated_(0);

/**
 * @brief Construct a new Thread:: Thread object
 *
 * @param func
 * @param name
 */
Thread::Thread(ThreadFunc func, const std::string &name)
    : started_(false), joined_(false), tid_(0), func_(std::move(func)), name_(name)
{
    setDefaultName();
}
/**
 * @brief Destroy the Thread:: Thread object
 *
 */
Thread::~Thread()
{
    if (started_ && !joined_)
    {
        thread_->detach();
    }
}
/**
 * @brief 开启线程
 *
 */
void Thread::start()
{
    started_ = true;
    sem_t sem;
    sem_init(&sem, false, 0);

    thread_ = std::shared_ptr<std::thread>(new std::thread([&]()
                                                           { 
    tid_ = CurrentThread::tid();//获取tid
    sem_post(&sem);
    func_(); })); // 执行线程函数
    // 等待获取tid
    sem_wait(&sem);
}
/**
 * @brief 关闭线程
 *
 */
void Thread::join()
{
    joined_ = true;
    thread_->join();
}
/**
 * @brief 给线程命名
 *
 */
void Thread::setDefaultName()
{
    int num = ++numCreated_;
    if (name_.empty())
    {
        char buff[32] = {0};
        sprintf(buff, "Thread%d", num);
        name_ = buff;
    }
}